import {log} from "@/util/Log.js"


export default (bus) => {
    const debug = false
    let connection = null
    let heartbeatTimer = null
    const reconnect = false
    let address = null
    let token = null
    const const_p = {
        0 : "websocket:error",
        1 : "websocket:close"
    }

    function init(key,fun){
        token = key
        let protocol = 'ws://';
        if (window.location.protocol === 'https:') {
            protocol = 'wss://';
        }
        if (!window.WebSocket) {
            //否则报错
            consol("不支持 socket 连接")
            return;
        }
        try {
            let host = window.location.hostname+':8083';
            address = protocol + host + '/webSocket?token=' + token;
            connection = new WebSocket(address);
        }catch (e){
            console.error(e)
        }
        // 打开连接
        connection.onopen = () => {
            consol("连接建立成功")
            // 自己维护心跳
            heartbeat()
            if(fun){
                fun()
            }
        };

        connection.onmessage = (message) => {
            consol("收到消息",message)
            let json = JSON.parse(message.data);
            if(json.type === 'ping'){
                heartbeat();
                return
            }
            bus.emit(json.type,json);
        };

        connection.onerror = (evt) => {
            consol("连接建立出错",evt)
            clearInterval(heartbeatTimer)
            bus.emit(const_p[0],evt);
        };

        connection.onclose = (evt) => {
            consol("关闭连接",evt)
            clearInterval(heartbeatTimer)
            reConnect();
            bus.emit(const_p[1],evt);
        };

    }

    function reConnect(){
        connection = null
        if(reconnect && !connection){
            setTimeout(() => init(token),3000)
        }
    }

    function heartbeat(){
        let msg = {
            type: "ping",
        }
        heartbeatTimer = setInterval(() =>{
            connection.send(JSON.stringify(msg));
        },10000)
    }

    function send(msg){
        let socketSend = setInterval(() => {
            if(!isConnect()){
                return
            }
            connection.send(JSON.stringify(msg));
            clearInterval(socketSend)
        },200)
    }

    function close(){
        clearInterval(heartbeatTimer)
        connection.close()
    }

    function consol(...args){
        if(debug){
            log.info(...args)
        }
    }
    function isConnect(){
        return connection && connection.readyState === 1
    }


    return {
        init,
        send,
        close,
        isConnect,
        const_p,
    }
}